package com.aliang.shardingjdbcdemo.conf;


import com.alibaba.druid.pool.DruidDataSource;
import org.apache.shardingsphere.api.config.masterslave.MasterSlaveRuleConfiguration;
import org.apache.shardingsphere.api.config.sharding.KeyGeneratorConfiguration;
import org.apache.shardingsphere.api.config.sharding.ShardingRuleConfiguration;
import org.apache.shardingsphere.api.config.sharding.TableRuleConfiguration;
import org.apache.shardingsphere.api.config.sharding.strategy.InlineShardingStrategyConfiguration;
import org.apache.shardingsphere.shardingjdbc.api.MasterSlaveDataSourceFactory;
import org.apache.shardingsphere.shardingjdbc.api.ShardingDataSourceFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @Author: chendongliang
 * @Date: 2019/8/23 14:32
 *
 *
 * 读写分离数据源配置
 *
 */
//@Configuration
public class DataSourceConfig1 {



    @Bean("dataSource")
    public DataSource getDataSource() throws SQLException {
        return buildDataSource();
    }

    private DataSource buildDataSource() throws SQLException {
        /*** 1.设置分库映射,数据源MAP ***/
        Map<String,DataSource> dataSourceMap =  new HashMap<>();
        dataSourceMap.put("master",createDataSource("ds_master"));
        dataSourceMap.put("ds_0",createDataSource("ds_0"));
        dataSourceMap.put("ds_1",createDataSource("ds_1"));


        /***
         * 配置读写分离规则,主从配置
         * master_salve 主从配置名
         * ds_2 主对应数据源
         * ds_0 ds_1 对应的数据源
         * @return
         */
        MasterSlaveRuleConfiguration masterSlaveRuleConfig = new MasterSlaveRuleConfiguration("ds_master_slave", "master", Arrays.asList("ds_0", "ds_1"));

        /*** 构建数据源 ***/
        Properties properties = new Properties();
        properties.put("sql.show",true);
        DataSource dataSource = MasterSlaveDataSourceFactory.createDataSource(dataSourceMap, masterSlaveRuleConfig, properties);

        return dataSource;
    }

    /***
     * 创建数据源
     *
     * ***/
    public static DataSource createDataSource(String dbName){

        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName("com.mysql.jdbc.Driver");
        druidDataSource.setUsername("root");
        druidDataSource.setPassword("123456");
        druidDataSource.setUrl(String.format("jdbc:mysql://116.62.18.242:3306/%s?characterEncoding=utf-8", dbName));

        return druidDataSource;
    }

}
